{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "726a5e16",
   "metadata": {},
   "source": [
    "### 5.1.1 优先使用异常捕获\n",
    "1. LBYL \"三思而后行\"编程风格"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "84f91662",
   "metadata": {},
   "outputs": [],
   "source": [
    "def incr_by_one(value):\n",
    "    \"\"\"对输入整数加1，返回新的值\n",
    "    \n",
    "    ：param value:整形，或者能转换成整形的字符串\n",
    "    ：return：整形结果\n",
    "    \"\"\"\n",
    "    if isinstance(value, int):\n",
    "        return value+1\n",
    "    elif isinstance(value, str) and value.isdigit():\n",
    "        return int(value)+1\n",
    "    else:\n",
    "        print(f'Unable to perform incr for value: \"{value}\"')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "20a7733f",
   "metadata": {},
   "source": [
    "2. EAFP 获取原谅比许可简单"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "72786146",
   "metadata": {},
   "outputs": [],
   "source": [
    "def incr_by_one(value):\n",
    "    \"\"\"对输入整数加1，返回新的值\n",
    "    \n",
    "    ：param value:整形，或者能转换成整形的字符串\n",
    "    ：return：整形结果\n",
    "    \"\"\"\n",
    "    try:\n",
    "        return int(value)+1\n",
    "    except (TypeError, ValueError) as e:\n",
    "        print(f'Unalbe to perform incr for value:\"{value}, error:{e}\"')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "569a003a",
   "metadata": {},
   "source": [
    "### 5.1.2 try语句常用知识"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "60635f66",
   "metadata": {},
   "outputs": [],
   "source": [
    "def safe_int(value):\n",
    "    \"\"\"尝试把输入转换为整数\"\"\"\n",
    "    try:\n",
    "        return int(value)\n",
    "    except TypeError:\n",
    "        \"\"\"当某类异常被抛出时，将会执行对应except下的语句\"\"\"\n",
    "        print(f'type error: {type(value)} is invalid')\n",
    "    except ValueError:\n",
    "        #你可以在一个try语句下写多个except\n",
    "        print(f'value error: {value} is invalid')\n",
    "    finally:\n",
    "        #finally里的语句，无论如何都会被执行，哪怕已经执行了return\n",
    "        print('function completed')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "755fec20",
   "metadata": {},
   "source": [
    "1. 更精确的excepte语句放在前面"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f033dbe0",
   "metadata": {},
   "outputs": [],
   "source": [
    "def incr_by_key(d, key):\n",
    "    try:\n",
    "        d[key]+=1\n",
    "    except KeyError:\n",
    "        print(f'key {key} does not exists')\n",
    "    except Exception as e:\n",
    "        print(f'Unknown error: {e}')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7c8966f7",
   "metadata": {},
   "source": [
    "2. 使用else分支"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "54cc5628",
   "metadata": {},
   "outputs": [],
   "source": [
    "#同步用户资料到外部系统，仅当同步成功时发送通知消息\n",
    "sync_succeeded = False\n",
    "try:\n",
    "    sync_profile(user.profile, to_extern = True)\n",
    "    sync_succeeded = True\n",
    "except Exception as e:\n",
    "    print(\"Error while suncing user profile\")\n",
    "else:\n",
    "    send_notification(user, 'profile sync succeeded')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "14ae75fa",
   "metadata": {},
   "source": [
    "3. 使用空raise语句"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "58db515f",
   "metadata": {},
   "outputs": [],
   "source": [
    "def incr_by_key(d, key):\n",
    "    try:\n",
    "        d[key]+=1\n",
    "    except KeyError:\n",
    "        print(f'key {key} does not exists, re-raise the exception')\n",
    "        raise"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "bd16a40b",
   "metadata": {},
   "source": [
    "### 5.1.3 抛出异常，而不是返回错误"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e4de17aa",
   "metadata": {},
   "outputs": [],
   "source": [
    "class CreateItemError(Exception):\n",
    "    \"\"\"创建item失败\"\"\"\n",
    "\n",
    "def create_item(name):\n",
    "    \"\"\"创建一个新的Item\n",
    "    :raise:当无法创建时抛出CreateItemError\n",
    "    \"\"\"\n",
    "    if len(name) > MAX_LENGTH_OF_NAME:\n",
    "        raise CreateItemError('names of otems is to long')\n",
    "    if len(get_current_items()) > MAX_ITEMS_QUOTA:\n",
    "        raise CreateItemError('items is full')\n",
    "    return Item(name = name)\n",
    "\n",
    "def create_from_input():\n",
    "    name = input()\n",
    "    try:\n",
    "        item = create_from_input(name)\n",
    "    except CreateItemError as e:\n",
    "        print(f'create item failed: {e}')\n",
    "    else:\n",
    "        print(f'item<{name}>created')\n",
    "    "
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d4929091",
   "metadata": {},
   "source": [
    "### 5.1.4 使用上下文管理器\n",
    "- 上下文管理器协议：实现 **__enter__** 和 **__exit__** 两个魔法方法"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "d6a40b36",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Name: foo-0.5611907527156993\n",
      "Exiting DummyContext\n"
     ]
    }
   ],
   "source": [
    "import random\n",
    "class DummyContext:\n",
    "    def __init__(self, name):\n",
    "        self.name = name\n",
    "    \n",
    "    def __enter__(self):\n",
    "        #__enter会在进入管理器时被调用，同时可以返回结果\n",
    "        #这个结果可以通过 as 关键字被调用方获取\n",
    "        #\n",
    "        #此处返回一个增加了随机后缀的name\n",
    "        return f'{self.name}-{random.random()}'\n",
    "    \n",
    "    def __exit__(self, exc_type, exc_val, exc_tb):\n",
    "        #__exit__会在退出管理器时被调用\n",
    "        print('Exiting DummyContext')\n",
    "        return False\n",
    "\n",
    "with DummyContext('foo') as name:\n",
    "    print(f'Name: {name}')    "
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2eaaad7e",
   "metadata": {},
   "source": [
    "1. 用于代替finally语句清理资源\n",
    "2. 用于忽略异常\n",
    "3. 使用contextmanager装饰器"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "6bad43f1",
   "metadata": {},
   "outputs": [],
   "source": [
    "class ignore_closed:\n",
    "    \"\"\"\"忽略已经关闭的连接\"\"\"\n",
    "\n",
    "    def __enter__(self):\n",
    "        pass\n",
    "\n",
    "    def __exit__(self, exc_type, exc_value, traceback):\n",
    "        if exc_type == AlreadyClosedError:\n",
    "            return True\n",
    "        return False\n",
    "    \n",
    "    with ignore_closed():\n",
    "        close_conn(conn)\n",
    "\n",
    "from contextlib import contextmanager\n",
    "\n",
    "@contextmanager\n",
    "def create_conn(host, port, timeout = timeout):\n",
    "    \"\"\"创建连接对象，并在退出上下文时自动关闭\"\"\"\n",
    "    conn = create_conn(host, port, timeout=timeout)\n",
    "    try:\n",
    "        yield conn\n",
    "    finally:\n",
    "        conn.closed()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0fd56a25",
   "metadata": {},
   "source": [
    "## 5.2 案例故事"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a3d88d7b",
   "metadata": {},
   "source": [
    "## 5.3 编程建议\n",
    "### 5.3.1 不要随便忽略异常\n",
    "### 5.3.2 不要手动做数据校验\n",
    "### 5.3.3 抛出可区分的异常\n",
    "### 5.3.4 不要使用assert来检查参数合法性\n",
    "### 5.3.5 无需处理是最好的参数处理\n",
    "- “空对象模式”"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d3faab7c",
   "metadata": {},
   "outputs": [],
   "source": [
    "def print_string(s):\n",
    "    assert isinstance(s, str), 's must be string'\n",
    "    print(s)\n",
    "print_string(1)\n",
    "\n",
    "def print_string1(s):\n",
    "    if not isinstance(s, str):\n",
    "        raise TypeError('s must be string')\n",
    "    print(s)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "196c0401",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "2\n"
     ]
    }
   ],
   "source": [
    "QUALIFIED_POINTS= 80\n",
    "\n",
    "class CreateUserPointError(Exception):\n",
    "    \"\"\"创建得分记录失败时抛出\"\"\"\n",
    "\n",
    "class UserPoint:\n",
    "    \"\"\"用户得分记录\"\"\"\n",
    "\n",
    "    def __init__(self, username, points):\n",
    "        self.username = username\n",
    "        self.points = points\n",
    "    \n",
    "    def is_qualified(self):\n",
    "        \"\"\"返回得分是否合格\"\"\"\n",
    "        return self.points >= QUALIFIED_POINTS\n",
    "    \n",
    "def make_userpoints(point_string):\n",
    "    \"\"\"从字符串初始化一条得分记录\n",
    "    :param point_string: 形如 piglei 1的表示得分记录的字符串\n",
    "    :return: UserPoint 对象\n",
    "    :raise: 当输入数据不合法时返回CreateUserPintError\n",
    "    \"\"\"\n",
    "    try:\n",
    "        username, points = point_string.split()\n",
    "        points = int(points)\n",
    "    except ValueError:\n",
    "        raise CreateUserPointError(\n",
    "            'input must follow pattern \"{username} {points}\"'\n",
    "        )\n",
    "    if points < 0:\n",
    "        raise CreateUserPointError('points can not be negative')\n",
    "    return UserPoint(username = username, points = points)\n",
    "\n",
    "def count_qualified(points_data):\n",
    "    \"\"\"计算得分合格的总人数\n",
    "\n",
    "    :param points_data:字符串格式的用户得分列表\n",
    "    \"\"\"\n",
    "    result = 0\n",
    "    for point_string in points_data:\n",
    "        try:\n",
    "            point_obj = make_userpoints(point_string)\n",
    "        except CreateUserPointError:\n",
    "            pass\n",
    "        else:\n",
    "            result += point_obj.is_qualified()\n",
    "    \n",
    "    return result\n",
    "\n",
    "data = [\n",
    "    'piglei 96',\n",
    "    'nobody 61',\n",
    "    'cotton 83',\n",
    "    'invalid_data',\n",
    "    'roland $invalid_points',\n",
    "    'alfred -3'\n",
    "]\n",
    "print(count_qualified(data))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "db2ffcb0",
   "metadata": {},
   "outputs": [],
   "source": [
    "QUALIFIED_POINTS= 80\n",
    "\n",
    "class CreateUserPointError(Exception):\n",
    "    \"\"\"创建得分记录失败时抛出\"\"\"\n",
    "\n",
    "class UserPoint:\n",
    "    \"\"\"用户得分记录\"\"\"\n",
    "\n",
    "    def __init__(self, username, points):\n",
    "        self.username = username\n",
    "        self.points = points\n",
    "    \n",
    "    def is_qualified(self):\n",
    "        \"\"\"返回得分是否合格\"\"\"\n",
    "        return self.points >= QUALIFIED_POINTS\n",
    "    \n",
    "class NullUserPoint:\n",
    "    \"\"\"一个空的用户得分记录\"\"\"\n",
    "\n",
    "    username = ''\n",
    "    points = 0\n",
    "\n",
    "    def is_qualified(self):\n",
    "        return False\n",
    "\n",
    "def make_userpoints(point_string):\n",
    "    \"\"\"从字符串初始化一条得分记录\n",
    "    :param point_string: 形如 piglei 1的表示得分记录的字符串\n",
    "    :return: UserPoint 对象\n",
    "    :raise: 当输入数据不合法时返回CreateUserPintError\n",
    "    \"\"\"\n",
    "    try:\n",
    "        username, points = point_string.split()\n",
    "        points = int(points)\n",
    "    except ValueError:\n",
    "        return NullUserPoint()\n",
    "    if points < 0:\n",
    "        return NullUserPoint()\n",
    "    return UserPoint(username = username, points = points)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "base",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.13.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
